package org.luxor.commons.websocket.component.session;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.luxor.commons.redis.annotation.RedisListener;
import org.luxor.commons.redis.component.RedisListenerReceiver;
import org.luxor.commons.websocket.component.protocol.AbstractCommand;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.Topic;

/**
 * 跨进程会话共享协作
 *
 * @author Mr.yan  @date 2021/9/4
 */
@RedisListener(channel = "WsShareSessionTopic")
public class WsShareProtocolReceiver implements RedisListenerReceiver {
    public static Topic WS_TOPIC = new ChannelTopic("WsShareSessionTopic");

    private static final String COMMAND = "command";
    private static final String TOKEN = "token";
    private static final String MESSAGE = "message";

    private WsShareSessionStorage sessionManager;

    public WsShareProtocolReceiver(WsShareSessionStorage sessionManager) {
        this.sessionManager = sessionManager;
    }

    @Override
    public void onMessage(String message, String channel) {
        JSONObject jsonMsg = JSONUtil.parseObj(message);
        String commandType = jsonMsg.getByPath(COMMAND, String.class);
        if (isRemoveCommand(commandType)) {
            String token = jsonMsg.getByPath(TOKEN, String.class);
            sessionManager.pureRemove(token);
        } else if (isSendCommand(commandType)) {
            String token = jsonMsg.getByPath(TOKEN, String.class);
            String textMessage = jsonMsg.getByPath(MESSAGE, String.class);
            sessionManager.pureSend(token, textMessage);
        } else if (isSendAllCommand(commandType)) {
            String textMessage = jsonMsg.getByPath(MESSAGE, String.class);
            sessionManager.pureSendAll(textMessage);
        }
    }

    /**
     * 移除指令？
     *
     * @return boolean
     */
    protected boolean isRemoveCommand(String command) {
        return AbstractCommand.REMOVE_COMMAND.equals(command);
    }

    /**
     * 发送指令？
     *
     * @return boolean
     */
    protected boolean isSendCommand(String command) {
        return AbstractCommand.SEND_COMMAND.equals(command);
    }

    /**
     * 群发指令？
     *
     * @return boolean
     */
    protected boolean isSendAllCommand(String command) {
        return AbstractCommand.SEND_ALL_COMMAND.equals(command);
    }
}
